"""
用户和权限相关模型
"""
from tortoise import fields
from .base import BaseModel


class User(BaseModel):
    """用户模型"""
    
    username = fields.CharField(max_length=50, unique=True, description="用户名")
    email = fields.CharField(max_length=100, unique=True, description="邮箱")
    hashed_password = fields.CharField(max_length=255, description="加密密码")
    full_name = fields.CharField(max_length=100, null=True, description="全名")
    phone = fields.CharField(max_length=20, null=True, description="电话")
    department = fields.CharField(max_length=100, null=True, description="部门")
    position = fields.CharField(max_length=100, null=True, description="职位")
    is_superuser = fields.BooleanField(default=False, description="是否超级用户")
    is_staff = fields.BooleanField(default=False, description="是否员工")
    last_login = fields.DatetimeField(null=True, description="最后登录时间")
    
    # 关联关系
    roles: fields.ManyToManyRelation["Role"] = fields.ManyToManyField(
        "models.Role", related_name="users", description="用户角色"
    )
    
    class Meta:
        table = "users"
        table_description = "用户表"


class Role(BaseModel):
    """角色模型"""
    
    name = fields.CharField(max_length=50, unique=True, description="角色名称")
    description = fields.TextField(null=True, description="角色描述")
    
    # 关联关系
    permissions: fields.ManyToManyRelation["Permission"] = fields.ManyToManyField(
        "models.Permission", related_name="roles", description="角色权限"
    )
    
    class Meta:
        table = "roles"
        table_description = "角色表"


class Permission(BaseModel):
    """权限模型"""
    
    name = fields.CharField(max_length=50, unique=True, description="权限名称")
    codename = fields.CharField(max_length=100, unique=True, description="权限代码")
    description = fields.TextField(null=True, description="权限描述")
    module = fields.CharField(max_length=50, description="所属模块")
    
    class Meta:
        table = "permissions"
        table_description = "权限表"


class UserSession(BaseModel):
    """用户会话模型"""
    
    user = fields.ForeignKeyField("models.User", related_name="sessions", description="用户")
    session_token = fields.CharField(max_length=255, unique=True, description="会话令牌")
    ip_address = fields.CharField(max_length=45, null=True, description="IP地址")
    user_agent = fields.TextField(null=True, description="用户代理")
    expires_at = fields.DatetimeField(description="过期时间")
    is_valid = fields.BooleanField(default=True, description="是否有效")
    
    class Meta:
        table = "user_sessions"
        table_description = "用户会话表"
